package com.aube.plugin.rank;

import com.aube.plugin.rank.model.CharacterProxy;
import com.aube.plugin.rank.model.RankModel;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.Character;
import com.huyn.baseframework.statesync.IDataObserver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * Created by huyaonan on 16/7/13.
 */
public class RankNumManager {

    public static final int RANK_1 = 0XFFFF9933;
    public static final int RANK_2 = 0XFF99CCFF;
    public static final int RANK_3 = 0XFFB03B00;
    public static final int RANK_4 = 0XFF666666;

    public static final int RANK_IMG_1 = R.drawable.icon_raise_1;
    public static final int RANK_IMG_2 = R.drawable.icon_raise_2;
    public static final int RANK_IMG_3 = R.drawable.icon_raise_3;
    public static final int RANK_IMG_4 = R.drawable.icon_raise_4;

    private static HashMap<String, HashMap<String, Integer>> mRankNums = new HashMap<>();

    private static HashMap<String, List<IDataObserver>> mRankItems = new HashMap<>();

    private static HashMap<String, Integer> mFavorCount = new HashMap<>();

    private static IDataObserver mWidgetObserver;

    private static IDataObserver mRankPageObserver;

    private static int mLeftChance = 0;
    private static String[] mKeys;

    public static int getTheme(int index) {
        switch (index) {
            case 0:
                return RANK_1;
            case 1:
                return RANK_2;
            case 2:
                return RANK_3;
            default:
                return RANK_4;
        }
    }

    public static int getRankImgRes(int index) {
        switch (index) {
            case 0:
                return RANK_IMG_1;
            case 1:
                return RANK_IMG_2;
            case 2:
                return RANK_IMG_3;
            default:
                return RANK_IMG_4;
        }
    }

    public static void registRankItem(String id, IDataObserver observer) {
        if(mRankItems == null)
            mRankItems = new HashMap<>();
        if(mRankItems.containsKey(id)) {
            mRankItems.get(id).add(observer);
        } else {
            List<IDataObserver> list = new ArrayList<>();
            list.add(observer);
            mRankItems.put(id, list);
        }
    }

    public static void registWidgetObserver(IDataObserver observer) {
        if(observer != null)
            mWidgetObserver = observer;
    }

    public static void registRankPageObserver(IDataObserver observer) {
        if(observer != null)
            mRankPageObserver = observer;
    }

    public static void unregistRankPageObserver() {
        mRankPageObserver = null;
    }

    public static void notifyItemChanged(String id) {
        if(mRankPageObserver != null)
            mRankPageObserver.stateUpdate();
        if(mWidgetObserver != null)
            mWidgetObserver.stateUpdate();

        if(mRankItems == null || !mRankItems.containsKey(id))
            return;
        List<IDataObserver> list = mRankItems.get(id);
        if(list != null && list.size() > 0) {
            for(IDataObserver observer : list)
                observer.stateUpdate();
        }
    }

    public static void notifyAllItemsChanged() {
        if(mRankPageObserver != null)
            mRankPageObserver.stateUpdate();
        if(mWidgetObserver != null)
            mWidgetObserver.stateUpdate();

        if(mRankItems == null || mRankItems.size() > 0)
            return;
        Iterator<List<IDataObserver>> valueIterator = mRankItems.values().iterator();
        if(valueIterator == null)
            return;
        while (valueIterator.hasNext()) {
            List<IDataObserver> list = valueIterator.next();
            if (list != null && list.size() > 0) {
                for (IDataObserver observer : list)
                    observer.stateUpdate();
            }
        }
    }

    public static void updateOperateConfig(Category category, List<RankModel> ranks) {
        String[] rankIds = new String[ranks.size()];

        int i=0;
        int votedNum=0;
        for(RankModel model : ranks) {
            rankIds[i] = model.getGroupKey();
            if(model.getVotedNum() > votedNum)
                votedNum = model.getVotedNum();
            i++;
        }

        Object countObj = category.getStrFromExtra("count");
        int count = 0;
        try {
            count = countObj != null ? Integer.parseInt((String) countObj) : 0;
        } catch (Exception e) {
            e.printStackTrace();
        }

        //投票数量超过约定数量,就不让继续投了
        if(votedNum >= count)
            count = 0;

        RankNumManager.updateOperateConfig(count, rankIds);
    }

    public static void updateOperateConfig(int count, String... keys) {
        mLeftChance = count;
        mKeys = keys;
    }

    public static void operateFavor(String id) {
        mLeftChance--;

        if(mRankNums == null || mKeys == null)
            return;

        for(String key : mKeys) {
            HashMap<String, Integer> map = mRankNums.get(key);
            int count = map.get(id) + 1;
            map.put(id, count);
        }

        if(mFavorCount == null)
            mFavorCount = new HashMap<>();

        if(mFavorCount.containsKey(id)) {
            mFavorCount.put(id, 1 + mFavorCount.get(id));
        } else {
            mFavorCount.put(id, 1);
        }

        notifyItemChanged(id);
    }

    public static int getFavorCount(String key, String id) {
        if(mKeys == null || mFavorCount == null)
            return 0;

        for(String str : mKeys) {
            if(str.equalsIgnoreCase(key)) {
                int result = mFavorCount.containsKey(id) ? mFavorCount.get(id) : 0;
                return result;
            }
        }

        return 0;
    }

    public static void initFavor(String key, String id, int count) {
        operateFavor(key, id, count, false);
    }

    public static void updateFavor(String key, String id, int count) {
        operateFavor(key, id, count, true);
    }

    private static void operateFavor(String key, String id, int count, boolean update) {
        if(mKeys == null)
            return;

        for(String str : mKeys) {
            if(str.equalsIgnoreCase(key)) {
                if(mFavorCount.containsKey(id)) {
                    if (mFavorCount.get(id) == count)
                        return;
                }
                mFavorCount.put(id, count);
                if(update)
                    notifyItemChanged(id);
            }
        }
    }

    public static boolean canOperate() {
        return mLeftChance > 0;
    }

    public static int getLeftChance() {
        return mLeftChance;
    }

    public static void updateItem(String key, String id, int num) {
        if(mRankNums == null)
            mRankNums = new HashMap<>();
        if(mRankNums.containsKey(key)) {
            HashMap<String, Integer> item = mRankNums.get(key);
            item.put(id, num);
        } else {
            HashMap<String, Integer> item = new HashMap<>();
            item.put(id, num);
            mRankNums.put(key, item);
        }
    }

    public static float getItemRatio(String key, String id) {
        if(mRankNums == null || !mRankNums.containsKey(key))
            return 0;
        int mMax = 0;
        Iterator<Integer> iterator = mRankNums.get(key).values().iterator();
        while (iterator.hasNext()) {
            int value = iterator.next();
            if(value > mMax)
                mMax = value;
        }
        if(mMax <= 0)
            return 0;
        return mRankNums.get(key).get(id)*1f/mMax;
    }

    public static int getItemNum(String key, String id) {
        if(mRankNums == null || !mRankNums.containsKey(key))
            return 0;
        return mRankNums.get(key).get(id);
    }

    public static boolean isPraised(Character character) {
        if(character != null)
            return "Y".equalsIgnoreCase(character.praised);
        return false;
    }

    public static String getRankIncreaseText(String key, Character character) {
        if(character != null && character instanceof CharacterProxy) {
            CharacterProxy proxy = (CharacterProxy) character;
            if(proxy.untilLastWeekCount == 0)
                return "";
            int count = getItemNum(key, character.relatedId);
            if(count == 0)
                count = character.praiseCount;
            if(count > 0)
                return "周上涨" + getRatio(count,proxy.untilLastWeekCount) + "%";
        }
        return "";
    }

    private static String getRatio(int count, int total) {
        String result = count * 100f/total + "";
        int dotIndex = result.indexOf(".");
        if(dotIndex < 0)
            return result;
        if(dotIndex+3 >= result.length())
            return result;
        return result.substring(0, dotIndex+3);
    }

}
